package com.runen.wnhz.runen.ui.activity.major;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.bean.LessonSmallSectionBean;
import com.runen.wnhz.runen.bean.UpdateSmallSelectionPlay;
import com.runen.wnhz.runen.bean.WantLearnBean;
import com.runen.wnhz.runen.common.login.Util;
import com.runen.wnhz.runen.common.login.Wx.WeiXinUtils;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.common.utils.Base64Utils;
import com.runen.wnhz.runen.common.utils.Constants;
import com.runen.wnhz.runen.common.utils.ImageUtils;
import com.runen.wnhz.runen.common.utils.NetStateUtils;
import com.runen.wnhz.runen.common.utils.NetUtils;
import com.runen.wnhz.runen.common.utils.OkHttpUtils;
import com.runen.wnhz.runen.common.utils.StatusBarCompatUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.data.entity.UserBean;
import com.runen.wnhz.runen.ui.activity.BasicActivity;
import com.runen.wnhz.runen.ui.activity.login.LoginForPersonalActivity;
import com.runen.wnhz.runen.ui.activity.main.DownloadActivity;
import com.runen.wnhz.runen.ui.adapter.puadapter.SmallSlectionRecyclerAdapter;
import com.runen.wnhz.runen.widget.SharePopWindow;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jzvd.JZVideoPlayerStandard;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class LookLessonActivity extends BasicActivity implements View.OnClickListener {

    @BindView(R.id.JZVideoPlayer)
    JZVideoPlayerStandard JZVideoPlayer;
    @BindView(R.id.linear_share_lesson)
    LinearLayout linearShareLesson;
    @BindView(R.id.linear_collect_lesson)
    LinearLayout linearCollectLesson;
    @BindView(R.id.linear_download_lesson)
    LinearLayout linearDownloadLesson;
    @BindView(R.id.recycler_lesson_period)
    RecyclerView recyclerLessonPeriod;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.image_collection)
    ImageView imageCollection;
    private String token;
    private boolean isCollected = false;
    private String lid;
    private SmallSlectionRecyclerAdapter adapter;
    private List<LessonSmallSectionBean.DataBean> dataBeans;
    private int position;

    SharePopWindow mPopwindow;
    private int shareType = QQShare.SHARE_TO_QQ_TYPE_DEFAULT;
    private Tencent mTencent;
    private String  QQAppID = "1107748313";

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    Bitmap bitmap = (Bitmap) msg.obj;
                    if(bitmap != null){
                      JZVideoPlayer.thumbImageView.setImageBitmap(bitmap);
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_look_lesson);
        StatusBarCompatUtils.getInstance().TranslucentStatusBar(this, R.color.title_green);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        initData();
        setListener();
        initView();
    }

    private void initData() {
        recyclerLessonPeriod.setLayoutManager(new GridLayoutManager(LookLessonActivity.this, 2));
        ACacheUtlis cacheUtlis = ACacheUtlis.getInstance();
        if (cacheUtlis != null) {
            UserBean reqeustUser = cacheUtlis.getReqeustUser(this);
            if (reqeustUser != null) {
                token = reqeustUser.getToken();
            }
        }
        lid = getIntent().getStringExtra("lid");
        String tid = getIntent().getStringExtra("tid");
        String nid = getIntent().getStringExtra("nid");
        getSmallSectionList(lid, tid, nid);
    }

    private void setListener() {
        ivBack.setOnClickListener(this);
        linearCollectLesson.setOnClickListener(this);
        linearDownloadLesson.setOnClickListener(this);
        linearShareLesson.setOnClickListener(this);
    }


    IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {
            if (shareType != QQShare.SHARE_TO_QQ_TYPE_IMAGE) {
               ToastUtil.showToast("QQShareActivity.this: onCancel: ");
            }
        }
        @Override
        public void onComplete(Object response) {
            // TODO Auto-generated method stub
            ToastUtil.showToast("LookLessonActivity.this: onComplete: " + response.toString());
        }
        @Override
        public void onError(UiError e) {
            // TODO Auto-generated method stub
            ToastUtil.showToast("LookLessonActivity.this: onError: " + e.errorMessage);
        }
    };

    private void getSmallSectionList(String lid, String tid, String nid) {
        if (lid != null && tid != null && nid != null && token != null) {
            FormBody formBody = new FormBody.Builder().add("token", token).add("lid", lid).add("tid", tid).add("nid", nid).build();
            Request request = new Request.Builder().url(NetUtils.USER_SMALL_SECTION).post(formBody).build();
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(request);
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("数据请求失败");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    handleData(response);
                }
            });
        }
    }

    private void handleData(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                final String json = responseBody.string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        LessonSmallSectionBean lessonSmallSectionBean = new Gson().fromJson(json, LessonSmallSectionBean.class);
                        if (lessonSmallSectionBean != null) {
                            if ("1".equals(lessonSmallSectionBean.getRe())) {
                                dataBeans = lessonSmallSectionBean.getData();
                                if (dataBeans != null && dataBeans.size() > 0) {
                                    LessonSmallSectionBean.DataBean dataBean = dataBeans.get(0);
                                    handleFirstData(dataBean);
                                }
                                adapter = new SmallSlectionRecyclerAdapter(dataBeans, LookLessonActivity.this);
                                recyclerLessonPeriod.setAdapter(adapter);
                            } else if ("0".equals(lessonSmallSectionBean.getRe())) {
                                ToastUtil.showToast(lessonSmallSectionBean.getInfo());
                            } else if ("-1".equals(lessonSmallSectionBean.getRe())) {
                                ToastUtil.showToast(lessonSmallSectionBean.getInfo());
                                startActivity(new Intent(LookLessonActivity.this, LoginForPersonalActivity.class));
                            }
                        }
                    }
                });
            }
        }
    }


    private void handleFirstData(LessonSmallSectionBean.DataBean dataBean) {
        String base64VideoUrl = Base64Utils.decode(dataBean.getTv_url());
        final String videoUrl = base64VideoUrl.substring(3, base64VideoUrl.length() - 5);
        new Thread(){
            @Override
            public void run() {
                Bitmap bitmap = ImageUtils.createVideoThumbnail(videoUrl, MediaStore.Images.Thumbnails.MINI_KIND);
                Message message = Message.obtain();
                message.what = 0;
                message.obj = bitmap;
                handler.sendMessage(message);
            }
        }.start();
        JZVideoPlayer.setUp(videoUrl, JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL, "");
        if (NetStateUtils.getNetWorkStatus(LookLessonActivity.this) == Constants.NETWORK_WIFI) {
            JZVideoPlayer.startVideo();
        } else if ((NetStateUtils.getNetWorkStatus(LookLessonActivity.this) != Constants.NETWORK_WIFI) && (preferences.getBoolean(Constants.SP_isAllowFluxWatch, false))) {
            JZVideoPlayer.startVideo();
            ToastUtil.showToast("当前正在使用流量播放视频哦");
        }
        if ("1".equals(dataBean.getIs_collect())) {
            isCollected = true;
            imageCollection.setImageResource(R.mipmap.have_want_learn_xin);
        }else{
            isCollected = false;
            imageCollection.setImageResource(R.mipmap.icon_want);
        }
    }

    private void saveWateLearn() {
        if (token != null && lid != null) {
            FormBody formBody = new FormBody.Builder().add("token", token).add("type", "2").add("id", lid).build();
            //构建一个网络请求，从指定网址上面请求数据
            Request.Builder requestBuilder = new Request.Builder()
                    .url(NetUtils.USER_LESSON_COLLECTION)
                    .post(formBody);
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(requestBuilder.build());
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("数据请求失败");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                handleWantLearnData(response);
                            } catch (IOException e) {
                                e.printStackTrace();
                                ToastUtil.showToast("数据请求出现异常");
                            }
                        }
                    });
                }
            });

        }
    }

    private void handleWantLearnData(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String json = responseBody.string();
                WantLearnBean wantLearnBean = new Gson().fromJson(json, WantLearnBean.class);
                if (wantLearnBean != null) {
                    if ("1".equals(wantLearnBean.getRe())) {
                        ToastUtil.showToast(wantLearnBean.getInfo());
                        imageCollection.setImageResource(R.mipmap.have_want_learn_xin);
                        isCollected = true;
                        dataBeans.get(position).setIs_collect("1");
                        adapter.notifyItemChanged(position);
                    } else if ("0".equals(wantLearnBean.getRe())) {
                        ToastUtil.showToast(wantLearnBean.getInfo());
                    }
                }
            }
        }

    }

    private void cancleWantCollection() {
        if (token != null) {
            FormBody formBody = new FormBody.Builder().add("token", token).add("type", "2").add("id", lid).add("del", "1").build();
            //构建一个网络请求，从指定网址上面请求数据
            Request.Builder requestBuilder = new Request.Builder()
                    .url(NetUtils.USER_LESSON_COLLECTION)
                    .post(formBody);
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(requestBuilder.build());
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("数据请求失败");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                handleCancleWantLearnData(response);
                            } catch (IOException e) {
                                e.printStackTrace();
                                ToastUtil.showToast("数据请求出现异常");
                            }
                        }
                    });
                }
            });
        }
    }

    private void handleCancleWantLearnData(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String json = responseBody.string();
                WantLearnBean wantLearnBean = new Gson().fromJson(json, WantLearnBean.class);
                if (wantLearnBean != null) {
                    if ("1".equals(wantLearnBean.getRe())) {
                        ToastUtil.showToast(wantLearnBean.getInfo());
                        imageCollection.setImageResource(R.mipmap.icon_want);
                        isCollected = false;
                        dataBeans.get(position).setIs_collect("0");
                        adapter.notifyItemChanged(position);
                    } else if ("0".equals(wantLearnBean.getRe())) {
                        ToastUtil.showToast(wantLearnBean.getInfo());
                    }
                }
            }
        }

    }

    @Subscriber
    public void onReceiveUpdateSmallSelectionPlayEvent(UpdateSmallSelectionPlay updateSmallSelectionPlay) {
        if (updateSmallSelectionPlay != null) {
            this.position = updateSmallSelectionPlay.getPosition();
            JZVideoPlayer.setUp(updateSmallSelectionPlay.getVideoUrl(), JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL,"");
            JZVideoPlayer.startVideo();
            boolean collected = updateSmallSelectionPlay.isCollected();
            isCollected = collected;
            if(collected){
                imageCollection.setImageResource(R.mipmap.have_want_learn_xin);
            }else{
                imageCollection.setImageResource(R.mipmap.icon_want);
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (cn.jzvd.JZVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        cn.jzvd.JZVideoPlayer.releaseAllVideos();
    }

    private void initView() {
        JZVideoPlayer.batteryLevel.setVisibility(View.GONE);
        JZVideoPlayer.mRetryLayout.setVisibility(View.GONE);
        JZVideoPlayer.backButton.setVisibility(View.GONE);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.linear_download_lesson:
                Intent intent = new Intent();
                intent.setClass(this, DownloadActivity.class);
                intent.putExtra("lid",lid);
                startActivity(intent);
                break;
            case R.id.linear_share_lesson:
                if (mTencent == null) {
                    mTencent = Tencent.createInstance(QQAppID, this);
                }
                 mPopwindow = new SharePopWindow(LookLessonActivity.this, itemsOnClick);
                mPopwindow.showAtLocation(view,
                        Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                 break;
            case R.id.linear_collect_lesson:
                if(isCollected){
                    cancleWantCollection();
                }else{
                    saveWateLearn();
                }
                break;

        }
    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            mPopwindow.dismiss();
            mPopwindow.backgroundAlpha(LookLessonActivity.this, 1f);
            final Bundle params = new Bundle();

            switch (v.getId()) {
                case R.id.weixinghaoyou:

                    share(false);
                    Toast.makeText(LookLessonActivity.this, "微信好友", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.pengyouquan:
                    share(true);
                    Toast.makeText(LookLessonActivity.this, "朋友圈", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.qqhaoyou:

                    params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
                    params.putString(QQShare.SHARE_TO_QQ_TITLE, "标题");
                    params.putString(QQShare.SHARE_TO_QQ_SUMMARY,"摘要");
                    params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,"http://blog.csdn.net/u013451048");
                    params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,"http://avatar.csdn.net/C/3/D/1_u013451048.jpg");
                    params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "CSDN");
                    mTencent.shareToQQ(LookLessonActivity.this, params, qqShareListener);


                    Toast.makeText(LookLessonActivity.this, "QQ好友", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.qqkongjian:
                    params.putInt(QQShare.SHARE_TO_QQ_EXT_INT,  QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
                    params.putString(QQShare.SHARE_TO_QQ_TITLE, "标题");
                    params.putString(QQShare.SHARE_TO_QQ_SUMMARY,"摘要");
                    params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,"https://mp.csdn.net/postedit/79887607");
                    ArrayList<String> imgUrlList = new ArrayList<>();
                    imgUrlList.add("http://f.hiphotos.baidu.com/image/h%3D200/sign=6f05c5f929738bd4db21b531918a876c/6a600c338744ebf8affdde1bdef9d72a6059a702.jpg");
                    params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL,imgUrlList);
                    params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "CSDN");
                    mTencent.shareToQzone(LookLessonActivity.this, params, qqShareListener);
                    Toast.makeText(LookLessonActivity.this, "QQ空间", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }

    };

    public void share(boolean friendsCircle){


            WXWebpageObject webpage = new WXWebpageObject();
            webpage.webpageUrl = "www.baidu.com";//分享url
            WXMediaMessage msg = new WXMediaMessage(webpage);
            msg.title = "分享标题";
            msg.description = "分享描述";
/*        Bitmap thumb = null;
        try {
            thumb = bmpFromURL(new URL("http://f.hiphotos.baidu.com/image/h%3D200/sign=6f05c5f929738bd4db21b531918a876c/6a600c338744ebf8affdde1bdef9d72a6059a702.jpg"));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
     *//*   try {
            thumb = BitmapFactory.decodeStream(new URL("http://f.hiphotos.baidu.com/image/h%3D200/sign=6f05c5f929738bd4db21b531918a876c/6a600c338744ebf8affdde1bdef9d72a6059a702.jpg").openStream());
        } catch (IOException e1) {
            e1.printStackTrace();
        }
*//*
//注意下面的这句压缩，120，150是长宽。

//一定要压缩，不然会分享失败

            Bitmap thumbBmp = Bitmap.createScaledBitmap(thumb,120,120,true);

//Bitmap回收

            thumb.recycle();

            msg.thumbData= Util.bmpToByteArray(thumbBmp,true);*/
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = msg;
            req.scene = friendsCircle ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
            WeiXinUtils.getInstance().getWxApi().sendReq(req);

//            msg.setThumbImage(thumb);

        }


//        msg.thumbData =getThumbData();//封面图片byte数组

    public static Bitmap bmpFromURL(URL imageURL){

        Bitmap result = null;

        try {

            HttpURLConnection connection = (HttpURLConnection)imageURL .openConnection();

            connection.setDoInput(true);

            connection.connect();

            InputStream input = connection.getInputStream();

            result = BitmapFactory.decodeStream(input);


        } catch (IOException e) {


            e.printStackTrace();

        }

        return result;

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == com.tencent.connect.common.Constants.REQUEST_QQ_SHARE) {
            Tencent.onActivityResultData(requestCode,resultCode,data,qqShareListener);
        } else if (requestCode == com.tencent.connect.common.Constants.REQUEST_QZONE_SHARE) {
            Tencent.onActivityResultData(requestCode,resultCode,data,qqShareListener);
        }
    }
}
